Insertion Sort in Java

Course- Java >

We can create a java program to sort array elements using insertion sort. Insertion is good for small elements only because it requires more time for sorting large number of elements.

insertion sort

Let's see a simple java program to sort an array using insertion sort algorithm.

 
  1. public class InsertionSortExample {  
  2.     public static void insertionSort(int array[]) {  
  3.         int n = array.length;  
  4.         for (int j = 1; j < n; j++) {  
  5.             int key = array[j];  
  6.             int i = j-1;  
  7.             while ( (i > -1) && ( array [i] > key ) ) {  
  8.                 array [i+1] = array [i];  
  9.                 i--;  
  10.             }  
  11.             array[i+1] = key;  
  12.         }  
  13.     }  
  14.        
  15.     public static void main(String a[]){    
  16.         int[] arr1 = {9,14,3,2,43,11,58,22};    
  17.         System.out.println("Before Insertion Sort");    
  18.         for(int i:arr1){    
  19.             System.out.print(i+" ");    
  20.         }    
  21.         System.out.println();    
  22.             
  23.         insertionSort(arr1);//sorting array using insertion sort    
  24.            
  25.         System.out.println("After Insertion Sort");    
  26.         for(int i:arr1){    
  27.             System.out.print(i+" ");    
  28.         }    
  29.     }    
  30. }    

Output:

Before Insertion Sort
9 14 3 2 43 11 58 22 
After Insertion Sort
2 3 9 11 14 22 43 58